from django import forms
from django.shortcuts import render,redirect,HttpResponse
from django.http import JsonResponse


#管理员首页
from django.views.decorators.csrf import csrf_exempt

from app02 import models
from app02.utils.bootrstap import BootrsapModelForm
from app02.utils.encrypt import md5
from app02.utils.pegination import Pegination


def admins_list(request):
    return render(request, 'admin_view.html')

#创建ModelForm
class CourseModelForm(BootrsapModelForm):
    class Meta:
        #关联表
        model=models.CourseTable
        fields='__all__'

#课表信息管理
def admins_course(request):
    if request.method == 'GET':
        title = '课程信息表'
        form_data = CourseModelForm()
        # 搜索框
        seach_list = request.GET.get('q', '')
        print(seach_list)
        data_t = {}
        # 搜索框中内容对应sections节次
        if seach_list:
            data_t['sections__contains'] = seach_list

        # 获取用户提交的信息
        dest = models.CourseTable.objects.filter(**data_t)

        # 分页
        page_object = Pegination(request, dest, page_size=6)
        context = {
            'dest': page_object.page_mun,
            'page_string': page_object.html(),
            'seach_list': seach_list,
            'title': title,
            'form_data': form_data
        }
        return render(request, "admin_course.html", context)

#新建课表信息
@csrf_exempt
def admins_addCourse(request):
    form_data=CourseModelForm(data=request.POST)
    if form_data.is_valid():
        form_data.save()
        data_dict={'static':True}
        return  JsonResponse(data_dict)
    return JsonResponse({'static':False,'error':form_data.errors})


#编辑课表窗口
def admins_EditGET(request):
    #获取id
    uid=request.GET.get('uid')
    # 根据id获取课程信息表对应的那一列的数据
    admins_obj=models.CourseTable.objects.filter(id=uid).values('sections','monday','tuesday','wednesday','thursday','friday').first()

    #判断数据存不存在
    if not admins_obj:
        return JsonResponse({'static':False,'error':'数据不存在'})
    result={'static':True,'data':admins_obj}
    return JsonResponse(result)

#编辑课程信息表
@csrf_exempt
def admins_EditCourse(request):
    #根据id获取课程信息表对应的那一列的数据
    uid=request.GET.get('uid')
    # 根据id获取课程信息表对应的那一列的数据
    admins_test=models.CourseTable.objects.filter(id=uid).first()
    if not admins_test:
        return JsonResponse({'static':False,'tpis':'数据不存在'})
    form_data=CourseModelForm(data=request.POST,instance=admins_test)
    if form_data.is_valid():
        form_data.save()
        return JsonResponse({'static':True})
    return HttpResponse(JsonResponse({'static':False,'error':form_data.errors}))

#删除课表
def admins_delete(request):
      uid=request.GET.get('uid')
      exits=models.CourseTable.objects.filter(id=uid).exists()
      if not exits:
          return JsonResponse({'static':False,'error':'删除失败，数据不存在'})
      models.CourseTable.objects.filter(id=uid).delete()
      return JsonResponse({'static':True})



#学生信息管理列表
#创建ModelForm
class StudentInfoModelForm(BootrsapModelForm):
    class Meta:
        #关联表
        model=models.StudentInfo
        exclude=['h_type']
def admins_studentList(request):
    if request.method=='GET':
        title='学生信息'
        form_data=StudentInfoModelForm()
        #搜索框
        seach_list = request.GET.get('t', '')
        print(seach_list)
        data_t={}
        #搜索框中内容对应sections节次
        if seach_list:
            data_t['user__contains']=seach_list

        #获取用户提交的信息
        class_dest=models.StudentInfo.objects.filter(**data_t)

        #分页
        page_object=Pegination(request,class_dest,page_size=6)
        context={
            'class_dest':page_object.page_mun,
            'page_string':page_object.html(),
            'seach_list':seach_list,
            'title': title,
            'form_data': form_data
        }

        return render(request,"admin_StudentInfo.html",context)

#新建学生信息
@csrf_exempt
def admins_studentAdd(request):
    form_data=StudentInfoModelForm(data=request.POST)
    if form_data.is_valid():
        pwd=form_data.cleaned_data.get('pwd')
        #判断是否获取到密码字段数据
        if pwd:
            #对密码进行md5加密
            encrypted_pwd=md5(pwd)
            form_data.cleaned_data['pwd'] =encrypted_pwd
        instance = form_data.save(commit=False)  # 创建一个模型实例，但不保存到数据库
        if pwd:
            instance.pwd = encrypted_pwd  # 将加密后的密码保存到模型实例的密码字段
        instance.save()
        data_dict={'static':True}
        return  JsonResponse(data_dict)
    return JsonResponse({'static':False,'error':form_data.errors})


#编辑学生信息窗口
def admins_studentEditGET(request):
    #获取id
    uid=request.GET.get('uid')
    # 根据id获取学生信息表对应的那一列的数据
    student_Object=models.StudentInfo.objects.filter(id=uid).values('id','user','pwd','StudentID','Studentage','Studentsex','Studentmodlie','teach').first()

    #判断数据存不存在
    if not student_Object:
        return JsonResponse({'static':False,'error':'数据不存在'})
    result={'static':True,'data':student_Object}
    return JsonResponse(result)

#编辑学生信息表
@csrf_exempt
def admins_studentEdit(request):
    #根据id获取课程信息表对应的那一列的数据
    uid=request.GET.get('uid')
    # 根据id获取课程信息表对应的那一列的数据
    student_test=models.StudentInfo.objects.filter(id=uid).first()
    if not student_test:
        return JsonResponse({'static':False,'tpis':'数据不存在'})
    form_data=StudentInfoModelForm(data=request.POST,instance=student_test)
    if form_data.is_valid():
        pwd = form_data.cleaned_data.get('pwd')
        # 判断是否获取到密码字段数据
        if pwd:
            # 对密码进行md5加密
            student_pwd = md5(pwd)
            form_data.cleaned_data['pwd'] = student_pwd
        instance = form_data.save(commit=False)  # 创建一个模型实例，但不保存到数据库
        if pwd:
            instance.pwd = student_pwd  # 将加密后的密码保存到模型实例的密码字段
        instance.save()
        return JsonResponse({'static':True})
    return HttpResponse(JsonResponse({'static':False,'error':form_data.errors}))

#删除学生信息
def admins_studentDelete(request):
      uid=request.GET.get('uid')
      exits=models.StudentInfo.objects.filter(id=uid).exists()
      if not exits:
          return JsonResponse({'static':False,'error':'删除失败，数据不存在'})
      models.StudentInfo.objects.filter(id=uid).delete()
      return JsonResponse({'static':True})


#教师信息管理列表
class TeacherInfoModelForm(BootrsapModelForm):
    class Meta:
        #关联表
        model=models.TeachInfo
        exclude=['h_type','teach']
def admins_teacherList(request):
    if request.method=='GET':
        title='教师信息'
        form_data=TeacherInfoModelForm()
        #搜索框
        seach_list = request.GET.get('t', '')
        print(seach_list)
        data_t={}
        #搜索框中内容对应sections节次
        if seach_list:
            data_t['user__contains']=seach_list

        #获取用户提交的信息
        class_dest=models.TeachInfo.objects.filter(**data_t)

        #分页
        page_object=Pegination(request,class_dest,page_size=6)
        context={
            'class_dest':page_object.page_mun,
            'page_string':page_object.html(),
            'seach_list':seach_list,
            'title': title,
            'form_data': form_data
        }

        return render(request,"admin_TeacherInfo.html",context)

#新建教师信息
@csrf_exempt
def admins_teacherAdd(request):
    form_data=TeacherInfoModelForm(data=request.POST)
    if form_data.is_valid():
        pwd=form_data.cleaned_data.get('pwd')
        #判断是否获取到密码字段数据
        if pwd:
            #对密码进行md5加密
            teacher_pwd=md5(pwd)
            form_data.cleaned_data['pwd'] =teacher_pwd
        instance = form_data.save(commit=False)  # 创建一个模型实例，但不保存到数据库
        if pwd:
            instance.pwd = teacher_pwd  # 将加密后的密码保存到模型实例的密码字段
        instance.save()
        data_dict={'static':True}
        return  JsonResponse(data_dict)
    return JsonResponse({'static':False,'error':form_data.errors})


#编辑教师信息窗口
def admins_teacherEditGET(request):
    #获取id
    uid=request.GET.get('uid')
    # 根据id获取学生信息表对应的那一列的数据
    teacher_Object=models.TeachInfo.objects.filter(id=uid).values('id','user','pwd','TeacherID','age','sex','modlie').first()

    #判断数据存不存在
    if not teacher_Object:
        return JsonResponse({'static':False,'error':'数据不存在'})
    result={'static':True,'data':teacher_Object}
    return JsonResponse(result)

#编辑教师信息表
@csrf_exempt
def admins_teacherEdit(request):
    #根据id获取课程信息表对应的那一列的数据
    uid=request.GET.get('uid')
    # 根据id获取课程信息表对应的那一列的数据
    teacher_test=models.TeachInfo.objects.filter(id=uid).first()
    if not teacher_test:
        return JsonResponse({'static':False,'tpis':'数据不存在'})
    form_data=TeacherInfoModelForm(data=request.POST,instance=teacher_test)
    if form_data.is_valid():
        pwd = form_data.cleaned_data.get('pwd')
        # 判断是否获取到密码字段数据
        if pwd:
            # 对密码进行md5加密
            encrypted_pwd = md5(pwd)
            form_data.cleaned_data['pwd'] = encrypted_pwd
        instance = form_data.save(commit=False)  # 创建一个模型实例，但不保存到数据库
        if pwd:
            instance.pwd = encrypted_pwd  # 将加密后的密码保存到模型实例的密码字段
        instance.save()
        return JsonResponse({'static':True})
    return HttpResponse(JsonResponse({'static':False,'error':form_data.errors}))

#删除教师信息
def admins_teacherDelete(request):
      uid=request.GET.get('uid')
      exits=models.TeachInfo.objects.filter(id=uid).exists()
      if not exits:
          return JsonResponse({'static':False,'error':'删除失败，数据不存在'})
      models.TeachInfo.objects.filter(id=uid).delete()
      return JsonResponse({'static':True})


#管理员信息管理列表
class AdminInfoModelForm(BootrsapModelForm):
    class Meta:
        #关联表
        model=models.AdminInfo
        exclude=['h_type','teach']
def admins_AdminsList(request):
    if request.method=='GET':
        title='管理员信息'
        form_data=AdminInfoModelForm()
        #搜索框
        seach_list = request.GET.get('t', '')
        print(seach_list)
        data_t={}
        #搜索框中内容对应user管理员
        if seach_list:
            data_t['user__contains']=seach_list

        #获取用户提交的信息
        class_dest=models.AdminInfo.objects.filter(**data_t)

        #分页
        page_object=Pegination(request,class_dest,page_size=6)
        context={
            'class_dest':page_object.page_mun,
            'page_string':page_object.html(),
            'seach_list':seach_list,
            'title': title,
            'form_data': form_data
        }

        return render(request,"admin_Info.html",context)

#新建管理员信息
@csrf_exempt
def admins_AdminsAdd(request):
    form_data=AdminInfoModelForm(data=request.POST)
    if form_data.is_valid():
        pwd=form_data.cleaned_data.get('pwd')
        #判断是否获取到密码字段数据
        if pwd:
            #对密码进行md5加密
            admin_pwd=md5(pwd)
            form_data.cleaned_data['pwd'] =admin_pwd
        instance = form_data.save(commit=False)  # 创建一个模型实例，但不保存到数据库
        if pwd:
            instance.pwd = admin_pwd  # 将加密后的密码保存到模型实例的密码字段
        instance.save()
        data_dict={'static':True}
        return  JsonResponse(data_dict)
    return JsonResponse({'static':False,'error':form_data.errors})


#编辑管理员信息窗口
def admins_AdminsEditGET(request):
    #获取id
    uid=request.GET.get('uid')
    # 根据id获取管理员信息表对应的那一列的数据
    admin_Object=models.AdminInfo.objects.filter(id=uid).values('id','user','pwd').first()

    #判断数据存不存在
    if not admin_Object:
        return JsonResponse({'static':False,'error':'数据不存在'})
    result={'static':True,'data':admin_Object}
    return JsonResponse(result)

#编辑管理员信息表
@csrf_exempt
def admins_AdminsEdit(request):
    #根据id获取管理员信息表对应的那一列的数据
    uid=request.GET.get('uid')
    # 根据id获取管理员信息表对应的那一列的数据
    Admin_test=models.AdminInfo.objects.filter(id=uid).first()
    if not Admin_test:
        return JsonResponse({'static':False,'tpis':'数据不存在'})
    form_data=AdminInfoModelForm(data=request.POST,instance=Admin_test)
    if form_data.is_valid():
        pwd = form_data.cleaned_data.get('pwd')
        # 判断是否获取到密码字段数据
        if pwd:
            # 对密码进行md5加密
            encrypted_pwd = md5(pwd)
            form_data.cleaned_data['pwd'] = encrypted_pwd
        instance = form_data.save(commit=False)  # 创建一个模型实例，但不保存到数据库
        if pwd:
            instance.pwd = encrypted_pwd  # 将加密后的密码保存到模型实例的密码字段
        instance.save()
        return JsonResponse({'static':True})
    return HttpResponse(JsonResponse({'static':False,'error':form_data.errors}))

#删除管理员信息
def admins_AdminsDelete(request):
      uid=request.GET.get('uid')
      exits=models.AdminInfo.objects.filter(id=uid).exists()
      if not exits:
          return JsonResponse({'static':False,'error':'删除失败，数据不存在'})
      models.AdminInfo.objects.filter(id=uid).delete()
      return JsonResponse({'static':True})

#请假管理
#学生请假管理
class AdminStudentLeaveModelForm(BootrsapModelForm):
    class Meta:
        #关联表
        model=models.StudentLeave
        fields='__all__'
def admins_StudentLeave(request):
    if request.method == 'GET':
        title = '请假信息'
        form_data =AdminStudentLeaveModelForm()
        # 搜索框
        seach_list = request.GET.get('q', '')
        data_t = {}
        # 搜索框中内容对应name姓名
        if seach_list:
            data_t['name__contains'] = seach_list

        # 获取用户提交的信息
        student_dest = models.StudentLeave.objects.filter(**data_t)

        # 分页
        page_object = Pegination(request, student_dest, page_size=6)
        context = {
            'student_dest': page_object.page_mun,
            'page_string': page_object.html(),
            'seach_list': seach_list,
            'title': title,
            'form_data': form_data
        }
        return render(request, "admin_Studentleave.html", context)

#新建请假信息
@csrf_exempt
def admins_StudentLeaveAdd(request):
    form_data=AdminStudentLeaveModelForm(data=request.POST)
    if form_data.is_valid():
        form_data.save()
        data_dict={'static':True}
        return  JsonResponse(data_dict)
    return JsonResponse({'static':False,'error':form_data.errors})

#审批窗口
def admins_StudentreportingGET(request):
    #获取id
    uid=request.GET.get('uid')
    # 根据id获取教师请假表对应的那一列的数据
    leave_Object=models.StudentLeave.objects.filter(id=uid).values('id','name','sex','age','xueID','test','times','retime','level','teachers','teacher_exam','admins','exam').first()

    #判断数据存不存在
    if not leave_Object:
        return JsonResponse({'static':False,'error':'数据不存在'})
    result={'static':True,'data':leave_Object}
    return JsonResponse(result)

#销假
@csrf_exempt
def admins_StudentLeaveReporting(request):
    #根据id获取教师请假信息表对应的那一列的数据
    uid=request.GET.get('uid')
    # 根据id获取教师请假信息表对应的那一列的数据
    leave_test=models.StudentLeave.objects.filter(id=uid).first()
    if not leave_test:
        return JsonResponse({'static':False,'tpis':'数据不存在'})
    form_data=AdminStudentLeaveModelForm(data=request.POST,instance=leave_test)
    if form_data.is_valid():
        form_data.save()
        return JsonResponse({'static':True})
    return HttpResponse(JsonResponse({'static':False,'error':form_data.errors}))

#删除请假
def admins_StudentDelete(request):
      uid=request.GET.get('uid')
      exits=models.StudentLeave.objects.filter(id=uid).exists()
      if not exits:
          return JsonResponse({'static':False,'error':'删除失败，数据不存在'})
      models.StudentLeave.objects.filter(id=uid).delete()
      return JsonResponse({'static':True})

#教师请假管理
class AdminTeacherLeaveModelForm(BootrsapModelForm):
    class Meta:
        #关联表
        model=models.TeacherLeave
        fields='__all__'
def admins_TeacherLeave(request):
    if request.method == 'GET':
        title = '请假信息'
        form_data =AdminTeacherLeaveModelForm()
        # 搜索框
        seach_list = request.GET.get('q', '')
        data_t = {}
        # 搜索框中内容对应name姓名
        if seach_list:
            data_t['name__contains'] = seach_list

        # 获取用户提交的信息
        teacher_dest = models.TeacherLeave.objects.filter(**data_t)

        # 分页
        page_object = Pegination(request, teacher_dest, page_size=6)
        context = {
            'teacher_dest': page_object.page_mun,
            'page_string': page_object.html(),
            'seach_list': seach_list,
            'title': title,
            'form_data': form_data
        }
        return render(request, "admin_Teacherleave.html", context)

#新建请假信息
@csrf_exempt
def admins_TeacherLeaveAdd(request):
    form_data=AdminTeacherLeaveModelForm(data=request.POST)
    if form_data.is_valid():
        form_data.save()
        data_dict={'static':True}
        return  JsonResponse(data_dict)
    return JsonResponse({'static':False,'error':form_data.errors})

#审批窗口
def admins_reportingGET(request):
    #获取id
    uid=request.GET.get('uid')
    # 根据id获取教师请假表对应的那一列的数据
    leave_Object=models.TeacherLeave.objects.filter(id=uid).values('id','name','sex','age','teacherID','test','times','retime','level','exam','admins').first()

    #判断数据存不存在
    if not leave_Object:
        return JsonResponse({'static':False,'error':'数据不存在'})
    result={'static':True,'data':leave_Object}
    return JsonResponse(result)

#销假
@csrf_exempt
def admins_TeacherLeaveReporting(request):
    #根据id获取教师请假信息表对应的那一列的数据
    uid=request.GET.get('uid')
    # 根据id获取教师请假信息表对应的那一列的数据
    leave_test=models.TeacherLeave.objects.filter(id=uid).first()
    if not leave_test:
        return JsonResponse({'static':False,'tpis':'数据不存在'})
    form_data=AdminTeacherLeaveModelForm(data=request.POST,instance=leave_test)
    if form_data.is_valid():
        form_data.save()
        return JsonResponse({'static':True})
    return HttpResponse(JsonResponse({'static':False,'error':form_data.errors}))

#删除请假
def admins_TeacherDelete(request):
      uid=request.GET.get('uid')
      exits=models.TeacherLeave.objects.filter(id=uid).exists()
      if not exits:
          return JsonResponse({'static':False,'error':'删除失败，数据不存在'})
      models.TeacherLeave.objects.filter(id=uid).delete()
      return JsonResponse({'static':True})


#教学评价信息管理
#学生填写信息提交表单
class StudnetRmationtableModelForm(BootrsapModelForm):
    class Meta:
        #关联表
        model=models.StudentInformationTable
        fields='__all__'
def admin_AdminRmationlist(request):
    if request.method == 'GET':
        title = '教学评价信息收集表'

        form_data =StudnetRmationtableModelForm()
        # 搜索框
        seach_list = request.GET.get('q', '')
        data_t = {}
        # 搜索框中内容对应数据库中字段
        if seach_list:
            data_t['StudentName__contains'] = seach_list

        # 获取用户提交的信息
        student_dest=models.StudentInformationTable.objects.filter(**data_t)


        # 分页
        page_object = Pegination(request,student_dest, page_size=6)
        context = {
            'student_dest':page_object.page_mun,
            'page_string': page_object.html(),
            'seach_list': seach_list,
            'title': title,
            'form_data': form_data,
        }
        return render(request, "admin_Information.html", context)

#审批窗口
def admin_RmationGET(request):
    #获取id
    uid=request.GET.get('uid')
    rmation_Object=models.StudentInformationTable.objects.filter(id=uid).values('id','StudentName','StudentID','sex','Texts','rmation','Filltime','teacherRmation','tables','examRmation','adminRmation').first()

    #判断数据存不存在
    if not rmation_Object:
        return JsonResponse({'static':False,'error':'数据不存在'})
    result={'static':True,'data':rmation_Object}
    return JsonResponse(result)

#审批
@csrf_exempt
def admin_RmationEdit(request):
    uid=request.GET.get('uid')
    rmation_test=models.StudentInformationTable.objects.filter(id=uid).first()
    if not rmation_test:
        return JsonResponse({'static':False,'tpis':'数据不存在'})
    form_data=StudnetRmationtableModelForm(data=request.POST,instance=rmation_test)
    if form_data.is_valid():
        form_data.save()
        return JsonResponse({'static':True})
    return HttpResponse(JsonResponse({'static':False,'error':form_data.errors}))

#删除发布信息
def admin_RmationDelete(request):
      uid=request.GET.get('uid')
      exits=models.StudentInformationTable.objects.filter(id=uid).exists()
      if not exits:
          return JsonResponse({'static':False,'error':'删除失败，数据不存在'})
      models.StudentInformationTable.objects.filter(id=uid).delete()
      return JsonResponse({'static':True})
